$(function(){
	
	var supplierId;
	var warehouseId;
	var cartGoods = {};
	
	
	$('.datepicker').datepicker({
	     format: "yyyy-mm-dd",
	     language: "zh-CN",
	     orientation: "top left",
	     autoclose:true
	});
	var dataTable = $('#supplierGoods').dataTable({
		"ColumnDefs" : [ {
	        sDefaultContent : '',
	        aTargets : [ '_all' ]
		} ],
		bFilter: false,
		"bPaginate": false,
        aaData: [],
        aoColumns: [
            {mDataProp:"taosku"},
            {mDataProp:"bn"},
            {mDataProp:"goodsName"},
            {mDataProp:"deliveryNum"},
            {mDataProp:"availableNum"},
            {mDataProp:"saleNumPerWeek"},
            {mDataProp:"salePrice"},
            {mDataProp:"recentPurchasePrice"},
            {mDataProp:"purchasePrice"},
            {mDataProp:"discountRate"},
            {mDataProp:"taxRate"},
            {mDataProp:"sizeSpec"},
            {mDataProp:"purchaseNum"},
            {mDataProp:"goodsAmount"},
            {mDataProp:"goodsId"},
            {mDataProp:"specId"}
        ],
        columnDefs:[{
        	targets:[8],
        	data:"purchasePrice",
        	render: function(data, type, full) {
                return "<input type='text' class='price userEdit' value="+ data+">";
            }
        },
        {
        	targets:[9],
        	data:"discountRate",
        	render: function(data, type, full) {
                return "<input type='text' class='rate userEdit' value='100'>";
            }
        } ,
        {
        	targets:[12],
        	data:"purchaseNum",
        	render: function(data, type, full) {
                return "<input type='text' class='buyAmount userEdit'  value=0>";
            }
        },
        {
        	targets:[13],
        	data:"totalAmount",
        	sClass:'amount',
        },
        {
        	targets:[14],
        	"bVisible": false,
        	data:"goodsId",
        },
        {
        	targets:[15],
        	"bVisible": false,
        	data:"goodsSpecId",
        }]
    } );
	$("#supplierGoods").on("change",".userEdit",function(){
		console.log($(this).val());
		var value = $(this).val();
		if(isNaN(value) || value<0)
		{
			alert("请输入正确数字！");
			return false;
		}
		var row = $(this).parents("tr");
		var price = row.find('.price').val();
		var buyAmount = row.find('.buyAmount').val();
		var totalAmount = row.find('.amount').val();
		var rate = row.find('.rate').val();
		var aData = dataTable.fnGetData($(row)); // get datarow
		
         if (null != aData && totalAmount!==0)  // null if we clicked on title row
         {
        	 aData['purchaseNum'] = value;
        	 computeTotalAmount(row);
             var goods = new GoodsDetail(aData['goodsId'],aData['goodsSpecId'],aData['taosku'],aData['bn'],aData['name'],0
             ,price,buyAmount,totalAmount,0,rate);
             cartGoods[aData['goodsId']] = goods;
         }
	});
	$.getJSON("/po_purchase/view?orderId="+GetQueryString("orderId"),null,function(data){
		$("#purchaseNo").text(data.orderCode);
		$(".discountAmount").val(data.discount);
		$("#address").val(data.address);
		$("#planArrivetime").val(data.planArrivetime);
		$(".prepayAmount").val(data.prePayAmount);
		$(".purchaseDate").val(data.purchaseDate);
		$(".planDate").val(data.purchaseDate);
		$("#demo").val(data.remark);
//		$(".payType").val(data.settmentName);
		$(".payType").val(data.settmentType);
		$("#supplierId").val(data.supplierId);
		supplierId = data.supplierId;
		$("#supplierName").text(data.supplierName);
		$(".amount").val(data.totalAmount);
		$(".warehouseSelect").val(data.warehouseId);
//		$("#warehouseName").val(data.warehouseName);
		var goods = data.orderGoodsDtoList;
		RefreshTableByData('#supplierGoods',goods);
		$.each(goods,function(i,aData){
			cartGoods[aData["goodsId"]] = new GoodsDetail(aData['goodsId'],aData['specId'],aData['taosku'],aData['bn'],aData['goodsName'],0
		             ,aData['purchasePrice'],aData['purchaseNum'],aData['goodsAmount'],0,aData['taxRate']);
		});
		var log = data.log;
		console.log(goods);
	});
	
	function getOrderValue(){
		var warehouseId=$(".warehouseSelect").val();
		var payType=$(".payType").val();
		var prepayAmount=$(".prepayAmount").val();
		var discountAmount = $(".discountAmount").val();
		var planDate = $(".planDate").val();
		var purchaseDate = $(".purchaseDate").val();
		var address = $("#address").val();
		var demo = $("#demo").val();
		var submitOrder = {};
		submitOrder.warehouseId=warehouseId;
		submitOrder.settmentType=payType;
		submitOrder.prepayAmount=prepayAmount ;
		submitOrder.discount=discountAmount ;
		submitOrder.planArrivetime=planDate;
		submitOrder.createTime=purchaseDate;
		submitOrder.address=address;
		submitOrder.remark=demo;
		submitOrder.supplierId = supplierId;
		submitOrder.warehouseId = warehouseId;
		var details = [];
		for(var p in cartGoods){
			if(cartGoods.hasOwnProperty(p)){
				details.push(cartGoods[p]);
			}
		}
		submitOrder.details = details;
		submitOrder = JSON.stringify(submitOrder);
		return submitOrder;
	}
	$(".submitOrder").click(function(){
		var data = getOrderValue();
		$.ajax({
			url:"editSubmit",
			type:'post',
			data:data,
			contentType: "application/json; charset=utf-8",
			dataType:"json",
			success:function(data){
				alert("修改成功！");
				var href = "purchaseOrderDetail?supplierId="+ supplierId+"&supplierName="+ $("#supplierName").val().replace(/\s+/g,"");
				$(".wrapper-content").load(href);
			},
			error:function(){
				
			}
		});
	});
	
	function RefreshTable(tableId, urlData)
    {
      //Retrieve the new data with $.getJSON. You could use it ajax too
      $.getJSON(urlData, null, function( json )
      {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.data.length; i++)
        {
          table.oApi._fnAddData(oSettings, json.data[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
      });
    }
	function RefreshTableByData(tableId,json)
    {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.length; i++)
        {
          table.oApi._fnAddData(oSettings, json[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    }
	function computeTotalAmount($row){
		var total = parseFloat($row.find('.price').val())*parseFloat($row.find('.rate').val())*parseInt($row.find('.buyAmount').val());
		$row.find('.amount').val(total);
	}
	function GetQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return (r[2]);
		return "";
	}
	function GoodsDetail(goodsId,goodsSpecId,taosku,bn,goodsName,isGift,taxPrice,orderNumber,taxAmount,receiveNumber,discountRate){
		var obj = {};
		obj.goodsId = goodsId;
		obj.goodsSpecId = goodsSpecId;
		obj.taosku = taosku;
		obj.bn = bn;
		obj.goodsName = goodsName;
		obj.isGift = isGift;
		obj.taxPrice = taxPrice;
		obj.orderNumber = orderNumber;
		obj.taxAmount = taxAmount;
		obj.receiveNumber = receiveNumber;
		obj.discountRate = discountRate;
		return obj;
	}
});
